package com.zy.util;

import com.zy.annotation.VarDesc;
import com.zy.bean.dto.BeanVarToJsonDto;

import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * Bean工具类
 *
 * @author hanhuafeng
 * @version V1.0
 * @description
 * @date 2023/7/18
 */
public class BeanUtil {
    /**
     * 把目标bean内部变量转换成json
     *
     * @param targetClass 目标bean
     * @return java.lang.String json字符串
     */
    public static <T> List<BeanVarToJsonDto> tranceVariableToJson(Class<T> targetClass) {
        // 取出目标bean的所有变量和变量类型
        Field[] declaredFields = targetClass.getDeclaredFields();
        List<BeanVarToJsonDto> result = new LinkedList<>();
        // 遍历变量
        for (Field declaredField : declaredFields) {
            BeanVarToJsonDto dto = new BeanVarToJsonDto();
            // 取出变量名
            String name = declaredField.getName();
            // 取出变量类型
            Class<?> type = declaredField.getType();
            Map<String, Object> properties = new LinkedHashMap<>();
            if (type.equals(String.class)) {
                properties.put("type", "text");
            } else if (type.equals(Integer.class) || type.equals(int.class)
                    || type.equals(Double.class) || type.equals(double.class)
                    || type.equals(Float.class) || type.equals(float.class)
                    || type.equals(Long.class) || type.equals(long.class)) {
                properties.put("type", "number");
            } else if (type.equals(Boolean.class) || type.equals(boolean.class)) {
                properties.put("type", "bool");
            } else if (type.equals(Date.class)
                    || type.equals(LocalDate.class)
                    || type.equals(Calendar.class)
                    || type.equals(LocalDateTime.class)) {
                properties.put("type", "date");
            } else {
                properties.put("type", type.getName());
            }
            VarDesc annotation = declaredField.getAnnotation(VarDesc.class);
            if (annotation != null) {
                properties.put("desc", annotation.value());
                properties.put("required", annotation.required());
            } else {
                properties.put("desc", name);
                properties.put("required", false);
            }
            dto.setVarName(name);
            dto.setProperties(properties);
            result.add(dto);
        }
        return result;
    }
}
